// 配置后端 Mock
// 需要 PATH 中有 curl 供调用；一般 Linux 与 Windows 10 都已预装

import mkdirp from 'mkdirp'; // eslint-disable-line import/no-extraneous-dependencies
import * as fs from 'fs';
import { execFileSync } from 'child_process';

import settings from '../src/lib/settings.mjs';

const VIDEO_MOCK = 'res/videoResultsMock.avi';
const VIDEO_MOCK_DOWNLOAD_URL = 'https://misaka-network.coding.net/api/share/download/059b5353-af38-41a7-8fe5-47da56deabc7';
const RESOURCE_DIR = 'res';
const BACKEND_SETTINGS_MOCK = {
  command: 'node',
  args: ['scripts/backendMock.mjs'],
};

function downloadExampleVideo() {
  mkdirp.sync(RESOURCE_DIR);
  try {
    execFileSync('curl', [
      '--output',
      VIDEO_MOCK,
      '--location',
      '--silent',
      '--show-error',
      '--fail',
      VIDEO_MOCK_DOWNLOAD_URL,
    ]);
  } catch (error) {
    if (fs.existsSync(VIDEO_MOCK)) {
      fs.unlinkSync(VIDEO_MOCK);
    }
    throw error;
  }
}

function setupMock() {
  settings.get('backend')
    .set('command', BACKEND_SETTINGS_MOCK.command)
    .set('args', BACKEND_SETTINGS_MOCK.args)
    .write();
}

try {
  if (!fs.existsSync(VIDEO_MOCK)) {
    console.log('正在下载示例视频...');
    downloadExampleVideo();
  } else {
    console.log('示例视频已存在');
  }
  console.log('正在更新设置...');
  setupMock();
  console.log(`配置完成，正在使用 ${BACKEND_SETTINGS_MOCK.args[BACKEND_SETTINGS_MOCK.args.length - 1]} 作为模拟后端`);
} catch (error) {
  console.log('出错:', error.message);
  process.exit(1);
}
